package com.minglead.springboot.platform.sys.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.minglead.springboot.common.crud.BaseController;
import com.minglead.springboot.common.persistence.Page;
import com.minglead.springboot.common.utils.StringUtils;
import com.minglead.springboot.platform.sys.entity.Area;
import com.minglead.springboot.platform.sys.service.AreaService;
import com.minglead.springboot.platform.sys.utils.ActionResponse;
import com.minglead.springboot.platform.sys.utils.UserUtils;
/**
 * 区域Controller
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/area")
public class AreaController extends BaseController {

	@Autowired
	private AreaService areaService;
	
	@ModelAttribute("area")
	public Area get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			return areaService.get(id);
		}else{
			return new Area();
		}
	}

/*	@RequiresPermissions("sys:area:view")*/
	@RequestMapping(value = {"list", ""})
	public String list(Area area, Model model) {
		model.addAttribute("typeList", Area.getTypeList());//区域类型
		return "modules/sys/areaList";
	}
	@RequestMapping(value="loadData")
	public void loadData(HttpServletRequest request, HttpServletResponse response){
		String name=request.getParameter("name");
		String code=request.getParameter("code");
		String type=request.getParameter("type");
		/******封装查询条件begin***********/
		Area area=new Area();
		area.setName(name);
		area.setCode(code);
		area.setType(type);
		/******封装查询条件end***********/
		Page<Area> page=new Page<Area>(request,response);
		Page<Area> areaPage=this.areaService.findPage(page, area);
		renderGrid(request, response, areaPage);
	}

/*	@RequiresPermissions("sys:area:view")*/
	@RequestMapping(value = "form")
	public String form(Area area,Model model) {
		model.addAttribute("typeList",Area.getTypeList());
		if (area.getParent()==null||area.getParent().getId()==null){
			area.setParent(UserUtils.getUser().getOffice().getArea());
		}
		if(area!=null&&area.getParent()!=null){
			area.setParent(areaService.get(area.getParent().getId()));
		}

		model.addAttribute("area", area);
		return "modules/sys/areaForm";
	}
	
/*	@RequiresPermissions("sys:area:edit")*/
	@RequestMapping(value = "save")
	public String save(Area area, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, area)){
			return form(area, model);
		}
		areaService.save(area);
		addMessage(redirectAttributes, "保存区域'" + area.getName() + "'成功");
		return "redirect:" + contextPath + adminPath + "/sys/area/";
	}
	
/*	@RequiresPermissions("sys:area:edit")*/
	@RequestMapping(value = "delete")
	public void delete(String id, HttpServletResponse response) {
		ActionResponse r = new ActionResponse(1,"操作成功！");
		if(StringUtils.isEmpty(id)){
			r.setMessage("删除失败,id不能为null");
			this.responseObject(r, response);
			return;
		}
		String[] _id = id.split(",");
		for(String id0:_id){
			Area area=new Area();
			area.setId(id0);
			areaService.delete(area);
		}
		this.responseObject(r, response);
	}
/*	@RequiresPermissions("user")*/
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required=false) String extId, HttpServletResponse response) {
		List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
		List<Area> list = areaService.findAll();
		for (int i=0; i<list.size(); i++){
			Area e = list.get(i);
			if (StringUtils.isBlank(extId) || (extId!=null && !extId.equals(e.getId()))){
				Map<String, Object> map = new HashMap<String,Object>();
				map.put("id", e.getId());
				map.put("pId", e.getParentId());
				map.put("name", e.getName());
				mapList.add(map);
			}
		}
		return mapList;
	}
	//省市级联
	@RequestMapping(value="getSubAreas")
	public void  getSubAreas(HttpServletResponse response,String code){ 
		List<Area> areas =  areaService.getSubListByCode(code);
		responseObject(areas, response);
	}

	//省市级联
	@RequestMapping(value="getParentAreas")
	public void  getTreeLevelsList(HttpServletResponse response,String code){ 
		List<Area> areas =  areaService.getTreeLevelsList(code);
		responseObject(areas, response);
	}
	
	/**
	 * 根据当前行政区划代码，获取下级list
	 * @param response
	 * @param code
	 */
	@RequestMapping(value="getSubAreaList")
	public void  getSubAreaList(HttpServletResponse response,String code){ 
		List<Area> areas =  areaService.getSubListByCode(code);
		responseObject(areas, response);
	}
	/**
	 * 获取当前节点兄弟节点
	 * @param response
	 * @param code
	 */
	@RequestMapping(value="getCurrentBrotherList")
	public void  getCurrentBrotherList(HttpServletResponse response,String code){ 
		Area currentNode = areaService.getEntityByCode(code);
		if(currentNode!=null){
			Area parent = areaService.get(currentNode.getParentId());
			String parentParentId = parent.getId();
			List<Area> brotherList = areaService.getSubListByParentId(parentParentId);
			
			for(Area area:brotherList){
				if(currentNode.getId().equals(area.getId())){
					area.setSelected(true);
					break;
				}
			}	
			responseObject(brotherList, response);
			return;
		}
		List<Area> emptyList =  new ArrayList<Area>();
		responseObject(emptyList, response);
	}
	
	
	/**
	 * 根据当前行政区划代码，获取父级兄弟节点列表，并且选择
	 * @param response
	 * @param code
	 */
	@RequestMapping(value="getParentBrotherList")
	public void  getParentBrotherList(HttpServletResponse response,String code){ 
		Area currentNode = areaService.getEntityByCode(code);
		if(currentNode!=null){
			Area parent = areaService.get(currentNode.getParentId());
			String parentParentId = parent.getParentId();
			List<Area> brotherList = areaService.getSubListByParentId(parentParentId);
			
			for(Area area:brotherList){
				if(parent.getId().equals(area.getId()))
					area.setSelected(true);
			}
			
			responseObject(brotherList, response);
			return;
		}
		List<Area> emptyList =  new ArrayList<Area>();
		responseObject(emptyList, response);
	}

	/**
	 * 根据当前行政区划代码，获取省级省级列表
	 * @param response
	 * @param code
	 */
	@RequestMapping(value="getProvinceList")
	public void  getProvinceList(HttpServletResponse response,String code){ 
		Area root = areaService.getRoot();
		List<Area> provinceList = areaService.getSubListByParentId(root.getId());
		for (int index = 0; index < provinceList.size(); index++) {
			//把广东放在首位
			if("440000".equals(provinceList.get(index).getCode())){
				Area guangDong = provinceList.get(index);
				provinceList.remove(index);
				provinceList.add(0, guangDong);
			}
		}
		Area currentNode = areaService.getEntityByCode(code);
		if(currentNode!=null){
			Area currentNode1 = areaService.get(currentNode.getParentId());
			if(currentNode1!=null){
				Area currentNode0 = areaService.get(currentNode1.getParentId());
				for(Area area:provinceList){
					if(currentNode0.getId().equals(area.getId()))
						area.setSelected(true);
				}	
		}
		}
		responseObject(provinceList, response);
		return;
	}

	/**
	 * 获取省级省级列表
	 * @param response
	 * @param code
	 */
	@RequestMapping(value="initProvinceList")
	public void  initProvinceList(HttpServletResponse response){
		Area root = areaService.getRoot();
		List<Area> provinceList = areaService.getSubListByParentId(root.getId());
		responseObject(provinceList, response);
		return;
	}
	
	
}
